// composables/useServerRequest.ts
import { useFetch, type UseFetchOptions } from "#app";

function isArray(str: unknown) {
  return Object.prototype.toString.call(str) === "[object Array]";
}

interface returnClass<T> {
  code: number;
  data: T;
  message: string;
}

let messageErrorNumber = 0;
function messageError(message: string) {
  if (messageErrorNumber <= 2) {
    messageErrorNumber++;
    naiveui.message.error(message, {
      onLeave() {
        messageErrorNumber--;
      },
    });
  }
}

export const useServerRequest = async <T = unknown>(
  url: string,
  opts: UseFetchOptions<T, unknown>
) => {
  const runtimeConfig = useRuntimeConfig();

  const defaultOptions: UseFetchOptions<unknown> = {
    baseURL: runtimeConfig.public.baseUrl,
    onRequest({ options }) {},
    onRequestError() {
      // 处理请求错误
      process.client && messageError("服务器链接失败!");
    },
    onResponse({ response }) {
      if (+response.status === 200) return;
      // 处理响应数据
      if (+response._data.code !== 0) {
        process.client && messageError(response._data.message || "onResponse");
      } else {
        process.client &&
          naiveui.message.success(response._data.message || "onResponse");
      }
    },
    onResponseError({ response }) {
      // 处理响应错误
      process.client &&
        messageError(
          isArray(response._data.message)
            ? response._data.message[0]
            : response._data.message || "onResponseError"
        );
    },
  };
  await nextTick();
  const res = await useFetch<returnClass<T>>(url, {
    ...defaultOptions,
    watch: false,
    ...opts,
  } as any);
  return res.data.value;
};
